from django.http import HttpResponseRedirect
from django.shortcuts import get_object_or_404
from django.urls import reverse_lazy
from django.views.generic import ListView, CreateView, UpdateView, TemplateView

from .models import Service


class ServicesListView(ListView):
    """ 服务列表 """
    template_name = "assets/services_list.html"
    model = Service
    context_object_name = "services_list_objs"


class ServicesCreateView(CreateView):
    """ 创建服务 todo 添加权限"""
    model = Service
    fields = ('name', 'port', 'remark')
    template_name = "assets/services_create.html"
    success_url = reverse_lazy("services_list")

    def form_valid(self, form):
        # todo
        """
        service_port = sf_post.cleaned_data.get('port')
        print
        service_port
        sf_post.save()
        if zabbix_on and service_port:
            ret = zabbix_template_add(request)
        """
        return super().form_valid(form)


class ServicesUpdateView(UpdateView):
    model = Service
    fields = ['name', 'port', 'remark']
    template_name = "assets/services_update.html"
    success_url = reverse_lazy("services_list")


class ServicesDeleteView(TemplateView):
    template_name = ""
    success_url = reverse_lazy("services_list")

    def get(self, request, *args, **kwargs):
        service = get_object_or_404(Service, pk=kwargs.get("pk"))
        service.host_set.clear()  # todo danager
        service.delete()
        return HttpResponseRedirect(self.success_url)
